package top.arryweb.application.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.arryweb.application.common.constant.KeyName;
import top.arryweb.application.domain.dto.CreatePaymentOrderDTO;
import top.arryweb.application.domain.pojo.BookKeepPaymentOrder;
import top.arryweb.application.mapper.BookKeepPaymentOrderMapper;
import top.arryweb.application.service.IBookKeepPaymentOrderService;

/**
 * <p>
 * 订单流水表 服务实现类
 * </p>
 *
 * @author astupidcoder
 * @since 2021-05-27
 */
@Service
public class BookKeepPaymentOrderServiceImpl extends
    ServiceImpl<BookKeepPaymentOrderMapper, BookKeepPaymentOrder> implements
    IBookKeepPaymentOrderService {

  @Autowired
  //@Qualifier("redisTemplate")
  private RedisTemplate<String, Object> redisTemplate;

  @Autowired(required = false)
  private BookKeepPaymentOrderMapper bookKeepPaymentOrderMapper;

  /**
   * 获取订单流水ID
   */
  @Override
  public Long getPaymentOrderId(CreatePaymentOrderDTO createPaymentOrderDTO) {
    Long merchantId = Optional.ofNullable(createPaymentOrderDTO.getMerchantId()).orElse(0L);
    Boolean distributionFlag = Optional.ofNullable(createPaymentOrderDTO.getDistributionFlag())
        .orElse(false);

    BookKeepPaymentOrder paymentOrder = new BookKeepPaymentOrder(createPaymentOrderDTO);
    paymentOrder.setMerchantId(merchantId);
    paymentOrder.setDistributionFlag(distributionFlag);
    paymentOrder.setPayStatus("TO_BE_PAID");
    paymentOrder.setVersion(0L);

    bookKeepPaymentOrderMapper.insert(paymentOrder);
    redisPut(paymentOrder);
    return paymentOrder.getId();
  }

  public void redisPut(BookKeepPaymentOrder paymentOrder) {
    //redis存储id
    HashOperations<String, Long, List<Long>> hashOperations = redisTemplate.opsForHash();
    HashOperations<String, Long, BookKeepPaymentOrder> orderOperations = redisTemplate.opsForHash();
    if (paymentOrder.getDistributionFlag()) {
      hashOperations
          .put(KeyName.IDS_ORDER_DIS.getName(), paymentOrder.getId(), new ArrayList<Long>());
    }
    hashOperations.put(KeyName.IDS_ORDER_TRADE.getName(), paymentOrder.getId(), new ArrayList<Long>());
    orderOperations.put(KeyName.ENTITY_ORDER.getName(), paymentOrder.getId(), paymentOrder);
  }

}
